package com.poly.police.monitor.application.service.sys.impl;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.poly.police.monitor.application.mapper.sys.SysAdminMapper;
import com.poly.police.monitor.application.mapper.sys.SysDeptMapper;
import com.poly.police.monitor.application.service.sys.ISysDeptService;
import com.poly.police.monitor.common.util.ListUtils;
import com.poly.police.monitor.pojo.entity.sys.SysAdmin;
import com.poly.police.monitor.pojo.entity.sys.SysDept;
import com.poly.police.monitor.pojo.validate.sys.SysDeptCreateValidate;
import com.poly.police.monitor.pojo.validate.sys.SysDeptSearchValidate;
import com.poly.police.monitor.pojo.validate.sys.SysDeptUpdateValidate;
import com.poly.police.monitor.pojo.vo.sys.SysDeptVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 系统部门服务实现类
 */
@Service
class SysDeptServiceImpl implements ISysDeptService {

    @Resource
    SysDeptMapper sysDeptMapper;

    @Resource
    SysAdminMapper sysAdminMapper;

    /**
     * 岗位所有
     *
     * @author fzr
     * @return List<SysDeptVo>
     */
    @Override
    public List<SysDeptVo> all() {
        List<SysDept> sysDeptList = sysDeptMapper.selectList(new QueryWrapper<SysDept>()
                .gt("pid", 0)
                .eq("is_delete", 0)
                .orderByDesc((Arrays.asList("sort", "id"))));

        List<SysDeptVo> list = new ArrayList<>();
        for (SysDept sysDept : sysDeptList) {
            SysDeptVo vo = new SysDeptVo();
            BeanUtils.copyProperties(sysDept, vo);
            list.add(vo);
        }

        return list;
    }

    /**
     *  部门列表
     *
     * @author fzr
     * @param searchValidate 搜索参数
     * @return JSONArray
     */
    @Override
    public JSONArray list(SysDeptSearchValidate searchValidate) {
        QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        queryWrapper.orderByDesc(Arrays.asList("sort", "id"));
        queryWrapper.select(SysDept.class, info ->
                !info.getColumn().equals("is_delete") &&
                !info.getColumn().equals("delete_time"));

        sysDeptMapper.setSearch(queryWrapper, searchValidate, new String[]{
                "monitor:name:str",
                "=:isStop@is_stop:int"
        });

        List<SysDept> sysDeptList = sysDeptMapper.selectList(queryWrapper);

        List<SysDeptVo> list = new LinkedList<>();
        for (SysDept sysDept : sysDeptList) {
            SysDeptVo vo = new SysDeptVo();
            BeanUtils.copyProperties(sysDept, vo);
            list.add(vo);
        }

        JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(list));
        return ListUtils.listToTree(jsonArray, "id", "pid", "children");
    }

    /**
     * 部门详情
     *
     * @author fzr
     * @param id 主键
     * @return SysDeptVo
     */
    @Override
    public SysDeptVo detail(Long id) {
        SysDept sysDept = sysDeptMapper.selectOne(
                new QueryWrapper<SysDept>()
                        .select(SysDept.class, info ->
                                !info.getColumn().equals("is_delete") &&
                                        !info.getColumn().equals("delete_time"))
                        .eq("id", id)
                        .eq("is_delete", 0)
                        .last("limit 1"));

        Assert.notNull(sysDept, "部门已不存在!");

        SysDeptVo vo  = new SysDeptVo();
        BeanUtils.copyProperties(sysDept, vo);
        return vo;
    }

    /**
     * 部门新增
     *
     * @author fzr
     * @param createValidate 参数
     */
    @Override
    public void add(SysDeptCreateValidate createValidate) {
        if (createValidate.getPid().equals(0)) {
            SysDept sysDept = sysDeptMapper.selectOne(
                    new QueryWrapper<SysDept>()
                            .select("id,pid,name")
                            .eq("pid", 0)
                            .eq("is_delete", 0)
                            .last("limit 1"));

            Assert.isNull(sysDept, "顶级部门只允许有一个");
        }

        SysDept model = new SysDept();
        model.setPid(createValidate.getPid());
        model.setName(createValidate.getName());
        model.setDuty(createValidate.getDuty());
        model.setMobile(createValidate.getMobile());
        model.setSort(createValidate.getSort());
        model.setIsStop(createValidate.getIsStop());
        model.setCreateTime(new Date());
        model.setUpdateTime(new Date());
        sysDeptMapper.insert(model);
    }

    /**
     * 部门编辑
     *
     * @author fzr
     * @param updateValidate 参数
     */
    @Override
    public void edit(SysDeptUpdateValidate updateValidate) {
        SysDept model = sysDeptMapper.selectOne(
                new QueryWrapper<SysDept>()
                        .select(SysDept.class, info ->
                           !info.getColumn().equals("is_delete") &&
                           !info.getColumn().equals("delete_time"))
                        .eq("id", updateValidate.getId())
                        .eq("is_delete", 0)
                        .last("limit 1"));

        Assert.notNull(model, "部门不存在");
        Assert.isFalse((model.getPid().equals(0) && updateValidate.getPid()>0), "顶级部门不能修改上级");
        Assert.isFalse(updateValidate.getId().equals(updateValidate.getPid()), "上级部门不能是自己");

        model.setPid(updateValidate.getPid());
        model.setName(updateValidate.getName());
        model.setDuty(updateValidate.getDuty());
        model.setMobile(updateValidate.getMobile());
        model.setSort(updateValidate.getSort());
        model.setIsStop(updateValidate.getIsStop());
        model.setUpdateTime(new Date());
        sysDeptMapper.updateById(model);
    }

    /**
     * 部门删除
     *
     * @author fzr
     * @param id 主键
     */
    @Override
    public void del(Long id) {
        SysDept model = sysDeptMapper.selectOne(
                new QueryWrapper<SysDept>()
                        .select("id,pid,name")
                        .eq("id", id)
                        .eq("is_delete", 0)
                        .last("limit 1"));

        Assert.notNull(model, "部门不存在");
        Assert.isFalse((model.getPid() == 0), "顶级部门不能删除");

        SysDept pModel = sysDeptMapper.selectOne(
                new QueryWrapper<SysDept>()
                        .select("id,pid,name")
                        .eq("pid", id)
                        .eq("is_delete", 0)
                        .last("limit 1"));

        Assert.isNull(pModel, "请先删除子级部门");

        SysAdmin sysAdmin = sysAdminMapper.selectOne(new QueryWrapper<SysAdmin>()
                .select("id,nickname")
                .eq("dept_id", id)
                .eq("is_delete", 0)
                .last("limit 1"));

        Assert.isNull(sysAdmin, "该部门已被管理员使用,请先移除");

        model.setIsDelete(1);
        model.setDeleteTime(new Date());
        sysDeptMapper.updateById(model);
    }

}